package com.epfresh.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.activity.CityAddressSelectedActivity;
import com.epfresh.activity.HomeActivity;
import com.epfresh.activity.SearchActivity;
import com.epfresh.adapter.MoreMarketAdapter;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.City;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.tablayout.SlidingTabLayout;
import com.epfresh.api.widget.tablayout.listener.OnTabSelectListener;
import com.epfresh.bean.HomeTopBean;
import com.epfresh.bean.Market;
import com.epfresh.global.BaseFragment;
import com.epfresh.global.DataManager;
import com.epfresh.utils.FileCache;
import com.epfresh.views.dialog.BaseDialogView;
import com.epfresh.views.dialog.MoreMarketDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wzh on 16-7-1.
 */
public class HomeFragment extends BaseFragment implements OnTabSelectListener {

    private SlidingTabLayout lyTab;
    private ViewPager vp;
    private PagerAdapter pagerAdapter;
    private ImageView ivMore;
    private ImageView ivCity;
    private TextView tvCity;


    private View llSearch;
//    private View vLine;

    private TopFragmentRecycler topFragment;
    private ArrayList<MarketHomeFragmentRecycler> marketReloadFlags = new ArrayList<>();
    public void reFreshTopFragment(){
        if(topFragment!=null)
            topFragment.mHttpOftenLoad(0,true);
    }
    public void reFreshTopFragmentStore(){
        if(topFragment!=null)
            topFragment.mHttpLoad();
    }

    public void showGoCartRed(boolean flag,boolean netFlag){
        if(topFragment!=null)
            topFragment.showGoCartRed(flag,netFlag);
    }

    @Override
    public String getBaseTag() {
        return "homeFragment";
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        return inflater.inflate(R.layout.fragment_home,
                container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        vLine = view.findViewById(R.id.v_line_3);



        llSearch = view.findViewById(R.id.ll_search);
        llSearch.setOnClickListener(this);
        tvCity = (TextView) view.findViewById(R.id.tv_city);
        ivCity = (ImageView) view.findViewById(R.id.iv_city);
        tvCity.setOnClickListener(this);
        ivCity.setOnClickListener(this);

        lyTab = (SlidingTabLayout) view.findViewById(R.id.ly_navigation);
        vp = (ViewPager) view.findViewById(R.id.vp);
        ivMore = (ImageView) view.findViewById(R.id.iv_more);
        lyTab.setOnTabSelectListener(this);
        ivMore.setOnClickListener(this);

        ivMore.setVisibility(View.GONE);
        if (pagerAdapter == null) {
            pagerAdapter = new FragmentStatePagerAdapter(getChildFragmentManager()) {
                @Override
                public Fragment getItem(int position) {
                    if (position == 0) {
                        if (topFragment == null) {
                            topFragment = new TopFragmentRecycler();
                        }
                        return topFragment;
                    } else {

                        MarketHomeFragmentRecycler marketFragment = new MarketHomeFragmentRecycler();
                        //MarketFragment marketFragment = new MarketFragment();
                        marketReloadFlags.add(marketFragment);
                        marketFragment.setMarketId(DataManager.getInstance().list.get(position - 1).getId());
                        return marketFragment;
                    }
                }

                @Override
                public int getCount() {
                    return DataManager.getInstance().list.size() + 1;
                }

                @Override
                public int getItemPosition(Object object) {
                    return POSITION_NONE;
                }

            };
        }
        vp.setOffscreenPageLimit(4);
        vp.setAdapter(pagerAdapter);

        tvCity.setText(ApplicationHelper.getInstance().getCity().getCityName());

        cacheRead();
        requestHome(ApplicationHelper.getInstance().getCity().getCityId(), ApplicationHelper.getInstance().getCity().getCityName(), null, null,true);
    }

    public void cacheRead() {
        FileCache fileCache = new FileCache(getAppApplication());
        String flag = fileCache.readFile(fileCache.getCachePath() + "home.json");
        Log.e("home_cache","take");
        if (flag != null && !"".equals(flag)&&topFragment!=null) {
            Log.e("home_cache","taking");
            HomeTopBean homeTopBean = new Gson().fromJson(flag, HomeTopBean.class);
            topFragment.initModels(homeTopBean);
        }
        if (flag != null && !"".equals(flag)) {
            try {
                JSONObject jo = new JSONObject(flag);

                JSONObject response = jo.getJSONObject("response");

                JSONArray markets = response.getJSONArray("markets");
                if (markets != null && markets.length() > 0) {
                    List<Market> marketList = new Gson().fromJson(markets.toString(), new TypeToken<List<Market>>() {
                    }.getType());
                    if (marketList != null && marketList.size() > 0) {
                        if (lyTab.getTabCount() > 0)
                            lyTab.setCurrentTab(0);
                        DataManager.getInstance().list.clear();
                        DataManager.getInstance().list.addAll(marketList);

                    }
                }
                loadView();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onTabSelect(int i) {
        MobclickAgent.onEvent(getContext(), "Click_Switch_HomeMarket");/*统计点击*/
        if (pop != null && pop.isShowing()) {
//            sortAdapter.setCurrentIndex(i-1);
//            sortAdapter.notifyDataSetChanged();
            pop.dismiss();
        }

        BaseDialogView.dismissRootView(getActivity());


    }

    @Override
    public void onTabReselect(int i) {

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()) {
            case R.id.ll_search:
                Intent search = new Intent(getActivity(), SearchActivity.class);
                startActivity(search);
                break;
            case R.id.iv_more:
                openMoreMarket();
                break;
            case R.id.tv_city:
            case R.id.iv_city:
                if (pop!=null && pop.isShowing()) {
                    pop.dismiss();
                }
                Intent address = new Intent(getActivity(), CityAddressSelectedActivity.class);
                startActivity(address);
                break;
        }
    }

    public MoreMarketDialog pop;

    MoreMarketAdapter adapter;


    private void openMoreMarket() {


        if (pop == null) {
            pop = new MoreMarketDialog(getContext());
            GridView gv = (GridView) pop.findViewById(R.id.gv_more);

            gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    lyTab.setCurrentTab(i + 1);
                    pop.dismiss();
                }
            });
            adapter = new MoreMarketAdapter(getContext(), DataManager.getInstance().list);

            gv.setAdapter(adapter);
            setGridviewHeight(gv);
            pop.setOnDismissListener(new BaseDialogView.OnDismissListener() {
                @Override
                public void onDismiss(Object o) {
                    ivMore.setImageResource(R.mipmap.home_more);
                }
            });

        }
        adapter.setCurrentIndex(lyTab.getCurrentTab() - 1);
        if (pop.isShowing()) {
            pop.dismiss();
//            ivMore.setImageResource(R.mipmap.home_more);
        } else {
//            vLine.setVisibility(View.VISIBLE);
            pop.show();
            adapter.notifyDataSetChanged();
            ivMore.setImageResource(R.mipmap.home_more_up);
        }
    }

    public void setGridviewHeight(GridView gridView)
    {
        if(DataManager.getInstance().list==null)
            return;
        if (DataManager.getInstance().list.size() > 15){
            RelativeLayout.LayoutParams params = (android.widget.RelativeLayout.LayoutParams) gridView.getLayoutParams();
            params.height = com.epfresh.api.utils.LocalDisplay.dp2px(250);//3*gridHeightFlag/((DataManager.getInstance().list.size()-1)/3+1);
            gridView.setLayoutParams(params);
        }
    }



//    List<Market> list = new ArrayList<>();

    public void loadView() {
        if(getActivity() == null){
            return;
        }
        //加载title
/*        DataManager.getInstance().list.addAll(DataManager.getInstance().list);
        DataManager.getInstance().list.addAll(DataManager.getInstance().list);*/
        String[] titles = new String[DataManager.getInstance().list.size() + 1];
        titles[0] = "推荐";
        for (int i = 0; i < DataManager.getInstance().list.size(); i++) {
            titles[i + 1] = DataManager.getInstance().list.get(i).getShortName() + "";
        }
        if (DataManager.getInstance().list.size() > 3) {
            ivMore.setVisibility(View.VISIBLE);
        } else {
            ivMore.setVisibility(View.GONE);
        }
//        lyTab.setTitles(titles);
        lyTab.setViewPager(vp, titles);
        pagerAdapter.notifyDataSetChanged();
    }

    public boolean isRequestHome = false;

    public void requestHome(final String cityId, final String cityName, String lng, String lat, final boolean showFlag) {
        isRequestHome = true;
        final RequestEntityMap requestEntity = new RequestEntityMap();
        requestEntity.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_homepage_purchaser);

        requestEntity.putParameter("cityId", cityId);
        requestEntity.putParameter("lng", lng);
        requestEntity.putParameter("lat", lat);

        requestEntity.setCityId(cityId);

        request(requestEntity, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_homepage_purchaser, new OnRequestListener<HomeTopBean>() {
            @Override
            public HomeTopBean jsonToObj(String s) {
                Log.e("ESD","HomeFragment-->AppPurchaseRouterConstant.cmd_store_homepage_purchaser接口"+ AppPurchaseRouterConstant.cmd_store_homepage_purchaser+"返回内容："+s);
                return new Gson().fromJson(s, HomeTopBean.class);
            }

            @Override
            public void onFail(int i, Object o, Object o1) {
                isRequestHome = false;
                hideProgressDialog();
            }

            @Override
            public void onResponseError(int i, Object o, Object o1) {
                isRequestHome = false;
                hideProgressDialog();


            }

            @Override
            public void onStart(Object o) {
                if(showFlag)
                    showProgressDialog();
            }

            @Override
            public void onResponse(ResponseEntity<HomeTopBean> responseEntity, Object o) {
                hideProgressDialog();



                String responseStr = responseEntity.getResponseStr();
                isRequestHome = false;
                if (responseStr != null) {
                    HomeTopBean responseElement = responseEntity.getResponseElement();

                    if (responseElement != null) {
//                        List<Market> markets = responseElement.getMarkets();
                        List<Market> markets = responseElement.getMarkets();
                        if (markets != null) {

                            FileCache fileCache = new FileCache(ApplicationHelper.getAppApplication());
                            fileCache.saveFile((fileCache.getCachePath() + "home.json"), responseStr);
                            City city = ApplicationHelper.getInstance().getCity();
                            String cn = responseElement.getCityName();
                            String cc = responseElement.getCityCode();

                            if (cn != null && !"".equals(cn) && cc != null && !"".equals(cc)) {

                            } else {
                                cn = cityName;
                                cc = cityId;
                            }

                            city.setCityId(cc);
                            city.setCityName(cn);

                            city.syncAddressId();
                            ApplicationHelper.getInstance().updateCity(city);
                            tvCity.setText(cn);

                            if (topFragment != null) {
                                topFragment.initModels(responseElement);
                                topFragment.mHttpOftenLoad(0,true);
                                topFragment.isCompleted();
                                //topFragment.clearDc();
                                //topFragment.requestDc(true);
                            }
                            if (lyTab.getTabCount() > 0)
                                lyTab.setCurrentTab(0);
                            DataManager.getInstance().list.clear();
                            DataManager.getInstance().list.addAll(markets);
                            if (getActivity() != null) {
                                ((HomeActivity) getActivity()).updateCategory();
                            }

                            loadView();

                            return;
                        }
                    }
                }

                T.toast("数据加载失败,请重试");
            }
        });
    }

    public void reLoginBack(){
        if (topFragment != null){
            //topFragment.requestDc(true);
            for(int i=0;i<marketReloadFlags.size();i++){
                if(marketReloadFlags.get(i)!=null)
                    return;
                    marketReloadFlags.get(i).firstSuccessFlag=false;
            }
        }
    }

/*
    public void requestDc(){
        if (topFragment != null ){
            topFragment.requestDc(true);
        }
    }
*/

    public int getCurrentIndex(){
        if (getActivity() != null && vp != null){
            return vp.getCurrentItem();
        }
        return -1;
    }
}
